package cn.tedu.store.commons.ex.handle;

import cn.tedu.store.commons.ex.ServiceException;
import cn.tedu.store.commons.web.JsonResult;
import cn.tedu.store.commons.web.ServiceCode;
import com.tencentcloudapi.common.exception.TencentCloudSDKException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.DisabledException;
import org.springframework.security.authentication.InternalAuthenticationServiceException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.validation.BindException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import javax.validation.ConstraintViolation;
import javax.validation.ConstraintViolationException;
import java.io.IOException;
import java.nio.file.AccessDeniedException;
import java.util.Set;

/**
 * 全局异常处理器
 *
 * @author RelentlessFlow
 * @version 0.0.1
 */
@Slf4j
@RestControllerAdvice
public class GlobalExceptionHandle {

    @ExceptionHandler
    public JsonResult<Void> handleServiceException(ServiceException e){
        log.warn("捕获到ServiceException 状态码:{}  信息:{}",e.getServiceCode().getValue(),e.getMessage());
        return JsonResult.fail(e);
    }

    @ExceptionHandler
    public JsonResult<Void> ConstraintViolationException(ConstraintViolationException e) {
        log.warn("捕获到ConstraintViolationException：{}", e.getMessage());
        StringBuilder sb = new StringBuilder();
        Set<ConstraintViolation<?>> constraintViolations = e.getConstraintViolations();
        for (ConstraintViolation<?> constraintViolation : constraintViolations) {
            sb.append(constraintViolation.getMessage());
        }
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,sb.toString());
    }


    @ExceptionHandler
    public JsonResult<Void> handleBindException(BindException e){
        log.debug("捕获到: BindException 描述:{}",e.getMessage());
        //配置了快速失败,只获取一个错误信息
        String message = e.getFieldError().getDefaultMessage();
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleIOException(IOException e){
        log.debug("捕获到: IOException 描述:{}",e.getMessage());
        String message = "服务器忙,请稍后再试!";
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }

    @ExceptionHandler
    public JsonResult<Void> handleTencentCloudSDKException(TencentCloudSDKException e){
        log.debug("捕获到: TencentCloudSDKException 描述:{}",e.getMessage());
        String message = "服务器忙,请稍后再试!";
        return JsonResult.fail(ServiceCode.ERR_BAD_REQUEST,message);
    }


    @ExceptionHandler
    public String handleHttpRequestMethodNotSupportedException(HttpRequestMethodNotSupportedException e) {
        log.warn("捕获到HttpRequestMethodNotSupportedException");
        return "非法访问！";
    }

    @ExceptionHandler({
            InternalAuthenticationServiceException.class, // AuthenticationServiceException >> AuthenticationException >> RuntimeException
            BadCredentialsException.class // AuthenticationException
    })
    public JsonResult handleAuthenticationException(AuthenticationException e) {
        log.debug("捕获到AuthenticationException");
        log.debug("异常类型：{}", e.getClass().getName());
        log.debug("异常信息：{}", e.getMessage());
        String message = "登录失败，用户名或密码错！";
        return JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED, message);
    }
    @ExceptionHandler
    public JsonResult handleAccessDeniedException(AccessDeniedException e) {
        log.debug("捕获到AccessDeniedException：{}", e.getMessage());
        String message = "操作失败，此管理员账号不具备此权限！";
        return JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED_DISABLE, message);
    }
    @ExceptionHandler
    public JsonResult handleDisabledException(DisabledException e) {
        log.debug("捕获到DisabledException：{}", e.getMessage());
        String message = "登录失败，此管理员账号已经被禁用！";
        return JsonResult.fail(ServiceCode.ERR_UNAUTHORIZED_DISABLE, message);
    }

    @ExceptionHandler
    public String handleThrowable(Throwable e){
        log.error("捕获到Throwable: {}",e.getMessage());
        e.printStackTrace();
        return "发生未知错误,请联系管理员";
    }
}
